package com.ruoyi.common.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.utils.JedisPoolUtil;
import com.ruoyi.common.utils.bean.WeixinAccount;
import com.ruoyi.common.utils.http.HttpUtils;
import com.alibaba.fastjson.JSONObject;

public class WeiXinHttpUtil {
	private static final Logger logger = LoggerFactory.getLogger(WeiXinHttpUtil.class);
	private static String APPID_KEY = "appId";
	private static String HD_URL_KEY = "hdUrl";
	private static String WEIXIN_ID_KEY = "weixinId";
	private static String NONCE_STR_KEY = "nonceStr";
	private static String TIMESTAMP_KEY = "timestamp";
	public static String TXT_ACTID_KEY = "txtActId";
	private static String get_Signature_URL;
	private static String getNickNameUrl;
	private static String getUserPhoneUrl;
	private static String getWeixinToken_URL;
	public static String appId;
	public static String weixinId;
	public static final String nonceStr = "oDxlNmsjqvV9D29r";
	// public static final boolean nonceStrflag = CommonRandomUtil.TRUE;
	public static final String timestamp = "1420942347";
	public static final String user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	public static final String user_info_sns_url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

	public static String getRedisSignature(HttpServletRequest request, String weixinId) {

		String signature = null;

		String url = request.getRequestURL() + "?" + request.getQueryString();

		String replaceUrl = url.replace(":8080", "");

		WeixinAccount po = JedisPoolUtil.getWxAccount(weixinId);
		if (po != null) {
			String jsapi_ticket = po.getJsapiticket();

			logger.info("==============getRedisSignature++++replaceUrl========" + replaceUrl);

			String need_make_string = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "&timestamp="
					+ timestamp + "&url=" + replaceUrl;
			try {
				signature = DigestUtils.shaHex(need_make_string);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			logger.info("-------------获取Signature失败-----------------");
			return null;
		}
		return signature;
	}

	public static String getSignature(String url) {
		String requestUrl = get_Signature_URL + weixinId + "&nonceStr=" + "oDxlNmsjqvV9D29r" + "&timestamp="
				+ "1420942347" + "&url=" + URLEncoder.encode(url);

		JSONObject jsonObj = HttpUtils.httpRequest(url, "POST", null);
		if (jsonObj.containsKey("signature")) {
			return jsonObj.getString("signature");
		}
		return "";
	}

	public static JSONObject getUserInfo(String openid, String access_token) {
		String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
		String replaceUrl = requestUrl.replace("OPENID", openid).replace("ACCESS_TOKEN", access_token);
		JSONObject jsonObj = HttpUtils.httpRequest(replaceUrl, "POST", null);

		return jsonObj;
	}

	public static String sign(HttpServletRequest request, String appid, String appsecret) {

		String url = request.getRequestURL() + "?" + request.getQueryString();
		String replaceUrl = url.replace(":8080", "");
		/*
		 * if (url.indexOf("#") != -1) { url = url.substring(0,
		 * url.indexOf("#"));
		 * System.err.println("----------url---------------------"+url); }
		 */
		System.err.println("----------replaceUrl---------------------" + replaceUrl);
		String jsapi_ticket = JsapiTicket(getAccessToken(appid, appsecret));
		Map<String, String> ret = new HashMap<String, String>();
		String string1;
		String signature = "";

		// 注意这里参数名必须全部小写，且必须有序
		string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr + "&timestamp=" + timestamp + "&url="
				+ replaceUrl;
		System.out.println("------------SIGN参数！！！！！！" + string1);

		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		ret.put("url", url);
		ret.put("jsapi_ticket", jsapi_ticket);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);

		return signature;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	private static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	private static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}

	// 网页授权接口
	public final static String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";

	public static String getAccessToken(String appid, String appsecret) {
		System.out.println(appid + "-------" + appsecret);
		String requestUrl = GetPageAccessTokenUrl.replace("APPID", appid).replace("SECRET", appsecret);
		JSONObject jsonObj = HttpUtils.httpRequest(requestUrl, "POST", null);
		String token = (String) jsonObj.get("access_token");
		return token;
	}

	// 网页授权接口
	public final static String GetPageticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";

	public static String JsapiTicket(String accessToken) {
		String requestUrl = GetPageticketUrl.replace("ACCESS_TOKEN", accessToken);
		JSONObject jsonObj = HttpUtils.httpRequest(requestUrl, "POST", null);
		String ticket = (String) jsonObj.get("ticket");
		return ticket;
	}

	public static JSONObject sendGet(String url) {
		JSONObject jsonObject = null;
		String result = "";
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
		try {
			URL realUrl = new URL(url);

			URLConnection connection = realUrl.openConnection();

			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.setConnectTimeout(3000);
			connection.setReadTimeout(30000);

			connection.connect();
			inputStream = connection.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream, "UTF-8");

			reader = new BufferedReader(inputStreamReader);
			String line;
			while ((line = reader.readLine()) != null) {
				result = result + line;
			}
			try {
				if (reader != null) {
					reader.close();
				}
				if (inputStreamReader != null) {
					inputStreamReader.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			jsonObject = JSONObject.parseObject(result);
		} catch (Exception e) {
			logger.info("发送GET请求出现异常" + e);
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
				if (inputStreamReader != null) {
					inputStreamReader.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return jsonObject;
	}

	public static JSONObject sendPost(String url) {
		JSONObject jsonObject = null;
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
		String result = "";
		try {
			URL realUrl = new URL(url);

			URLConnection conn = realUrl.openConnection();

			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setConnectTimeout(3000);
			conn.setReadTimeout(30000);
			inputStream = conn.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream, "UTF-8");

			reader = new BufferedReader(inputStreamReader);
			String line;
			while ((line = reader.readLine()) != null) {
				result = result + line;
			}
			try {
				if (reader != null) {
					reader.close();
				}
				if (inputStreamReader != null) {
					inputStreamReader.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			jsonObject = JSONObject.parseObject(result);
		} catch (Exception e) {
			logger.info("发送POST请求出现异常" + e);
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
				if (inputStreamReader != null) {
					inputStreamReader.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return jsonObject;
	}

	
	  public static JSONObject getGzUserInfo(String openid, String weixinId)
	  {
	    WeixinAccount wxAccount = JedisPoolUtil.getWxAccount(weixinId);
	    String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN".replace("ACCESS_TOKEN",wxAccount.getAccountaccesstoken());
	    requestUrl = requestUrl.replace("OPENID", openid);
	    JSONObject jsonObj = sendGet(requestUrl);
	    if ((jsonObj != null) && (!jsonObj.containsKey("errcode"))) {
	      logger.info("-----------------getGzUserInfo--------------------" + jsonObj.toString());
	      return jsonObj;
	    }
	    
	    return null;
	  }
	  


	  
	

}
